<!DOCTYPE HTML>
<html lang="zh-CN">
<head>
 <meta charset="UTF-8" />
 <script type="text/javascript" src="jquery.min.1.8.3.js"></script>
 <style type="text/css">
  .box{
   padding:10px;
  }
  .picBox{
   width:265px;
   height:137px;
   border:1px dashed #999;
  }
  .picBox img{
   width:100%;
   height:100%;
   display:block;
  }
 </style>
 <title>jQuery/JavaScript 实现的异步加载图片</title>
</head>
<body>
 <!-- S jqAjax -->
 <div id="jqAjax" class="box">
  <input type="submit" value="jQuery 异步加载图片" id="jqAjaxBtn" />
  <div class="picBox">
   <img data-src="logo.png" src="loading.gif" alt="" class="logo" />
  </div>
  <script type="text/javascript" src="jquery-1.8.3.min.js"></script>
  <script>
   $(document).ready(function(){
    $('#jqAjaxBtn').toggle(
     function(){
      var imgSrc = $(this).next().find('.logo').attr('data-src');
      $(this).next().find('.logo').attr('src', imgSrc);
      $(this).attr('value','再玩一次 O(∩_∩)O~');
     },
     function(){
      $(this).next().find('.logo').attr('src', 'loading.gif');
      $(this).attr('value','jQuery 异步加载图片');
     }
    );
   });
  </script>
 </div>
 <!-- E jqAjax -->
 
 <!-- S jsAjax -->
 <div id="jsAjax" class="box">
  <input type="submit" value="JavaScript 异步加载图片" id="jsAjaxBtn" />
  <div class="picBox">
   <img data-src="logo.png" src="loading.gif" alt="" class="logo" />
  </div>
  <script>
   window.onload = function(){
    document.getElementById('jsAjaxBtn').onclick = jsToggle;
   }
   function jsToggle(){
    var jsImgTag = document.getElementById('jsAjax').getElementsByTagName('img')[0];
    var jsImgDataSrc = jsImgTag.getAttribute('data-src');
    var jsImgSrc = jsImgTag.getAttribute('src',2);
    if ( jsImgSrc == 'loading.gif' ){
     jsImgTag.setAttribute('src',jsImgDataSrc);
     document.getElementById('jsAjaxBtn').setAttribute('value','再玩一次 O(∩_∩)O~');
    } else {
     jsImgTag.setAttribute('src','loading.gif');
     document.getElementById('jsAjaxBtn').setAttribute('value','JavaScript 异步加载图片');
    }
   }
  </script>
 </div>
 <!-- E jsAjax -->
</body>
</html>
